package com.seqb.common.mybatis;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.seqb.annotation.Ignored;
import com.seqb.utils.GenUtils;
import com.seqb.utils.ReflectUtils;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * @author lils
 * @title 请填写标题
 * @description 请填写相关描述
 * @date 2019/11/15
 */
public class WrapperHandler {

    /**
     * 构造一个queryWrapper
     */
    public static QueryWrapper genQueryWrapper(Map<String, Object> params, Class clazz) {
        if (null == params || null == clazz) {
            return null;
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        try {
            Field[] declaredFields = clazz.getDeclaredFields();
            for (int i = 0; i < declaredFields.length; i++) {
                Field field = declaredFields[i];
                String name = field.getName();
                Object object = params.get(name);
                if (null != object) {
                    String value = String.valueOf(object);
                    if (value.startsWith("%") || value.endsWith("%")) {
                        queryWrapper.like(GenUtils.humpToUnderline(name), value);
                    } else if (StringUtils.isNotEmpty(value)) {
                        queryWrapper.eq(GenUtils.humpToUnderline(name), value);
                    }
                }
            }
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                String name = entry.getKey();
                Object object = entry.getValue();
                if ("sort".equals(name)) {
                    queryWrapper.orderByAsc(GenUtils.humpToUnderline(String.valueOf(object)));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return queryWrapper;
    }

    /**
     * 构造一个updateWrapper
     */
    public static UpdateWrapper genUpdateWrapper(Object object) {
        if (null == object) {
            return null;
        }
        UpdateWrapper updateWrapper = new UpdateWrapper();
        try {
            Field[] declaredFields = object.getClass().getDeclaredFields();
            for (Field field : declaredFields) {
                Ignored ignored = field.getDeclaredAnnotation(Ignored.class);
                if (null != ignored) {
                    String fieldName = field.getName();
                    Object value = ReflectUtils.getFieldValueByName(fieldName, object);
                    if (null == value) {
                        updateWrapper.set(GenUtils.humpToUnderline(fieldName), null);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return updateWrapper;
    }

}
